using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections.Specialized;


namespace ProjectBase.Utils
{
    public class CMail
    {
        #region Create Instance
        private static CMail instance = null;
        public static CMail Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CMail();
                }
                return instance;
            }
        }
        #endregion

        #region CMail class

        public bool IsValidEmail(string email)
        {
            return Regex.IsMatch(email, @"^([0-9a-z]+[-._+&])*[0-9a-z]+@([-0-9a-z]+[.])+[a-z]{2,6}$", RegexOptions.IgnoreCase);
        }
        // Doc file template
        public string ReadTemplate(string wsRoot, string name)
        {
            string file;

            if (HttpContext.Current.Cache[name] != null)
            {
                file = HttpContext.Current.Cache[name].ToString();
            }
            else
            {
                string templatefile = HttpContext.Current.Server.MapPath(String.Format("{0}/Templates/Mail/{1}", wsRoot, name));
                StreamReader sr = new StreamReader(templatefile, Encoding.Unicode);
                file = sr.ReadToEnd();
                sr.Close();
                HttpContext.Current.Cache[name] = file;
            }

            return file;
        }
        // Tao email tu mau co san
        public string CreateEmailFromTemplate(string pathRoot, string templateName, ref StringDictionary templateParameters)
        {
            string email = ReadTemplate(pathRoot, templateName);

            foreach (string key in templateParameters.Keys)
            {
                email = email.Replace(key, templateParameters[key]);
            }

            return email;
        }
        //Tao thong diep mail gui
        public void SendMail(string fromEmail, string toEmail, string subject, string body)
        {
            string smtpMail = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
            fromEmail = fromEmail.Equals("") ? smtpMail : fromEmail;
            toEmail = toEmail.Equals("") ? smtpMail : toEmail;
            SendMail(new System.Net.Mail.MailAddress(fromEmail), new System.Net.Mail.MailAddress(toEmail), subject, body);
        }
        public void SendMultiMail(string fromEmail, string toEmail, string subject, string body)
        {
            string emails = toEmail.Replace(" ", "");
            string[] e = toEmail.Split(',');
            foreach (string em in e)
            {
                SendMail(new System.Net.Mail.MailAddress(fromEmail), new System.Net.Mail.MailAddress(em), subject, body);
            }
        }
        public void SendMultiMail(string fromEmail, ICollection<string> toEmail, string subject, string body)
        {
            SendMultiMail(new System.Net.Mail.MailAddress(fromEmail), toEmail, subject, body);
        }
        public void SendMail(string fromEmail, string fromName, string toEmail, string toName, string subject, string body)
        {
            string smtpMail = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
            string smtpName = System.Configuration.ConfigurationSettings.AppSettings["AdminName"];
            fromName = fromName.Equals("") ? smtpName : fromName;
            fromEmail = fromEmail.Equals("") ? smtpMail : fromEmail;
            SendMail(new System.Net.Mail.MailAddress(fromEmail, fromName), new System.Net.Mail.MailAddress(toEmail, toName), subject, body);
        }
        //Thuc hien send mail
        public void SendMail(System.Net.Mail.MailAddress fromAddress, System.Net.Mail.MailAddress toAddress, string subject, string body)
        {
            string smtpUserName = System.Configuration.ConfigurationSettings.AppSettings["SmtpUserName"];
            string smtpUserPass = System.Configuration.ConfigurationSettings.AppSettings["SmtpUserPass"];
            string smtpServer = System.Configuration.ConfigurationSettings.AppSettings["SmtpServer"];
            string smtpMail = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
            string smtpName = System.Configuration.ConfigurationSettings.AppSettings["AdminName"];

            System.Net.Mail.SmtpClient smtpSend = new System.Net.Mail.SmtpClient(smtpServer);
            //Cho gmail
            //System.Net.Mail.SmtpClient smtpSend = new System.Net.Mail.SmtpClient(smtpServer,587);

            if (!smtpUserName.Equals("") && !smtpUserPass.Equals(""))
            {
                smtpSend.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpUserPass);
            }

            using (System.Net.Mail.MailMessage emailMessage = new System.Net.Mail.MailMessage())
            {
                emailMessage.To.Add(toAddress);
                emailMessage.From = fromAddress.Equals(null) ? new System.Net.Mail.MailAddress(smtpMail, smtpName) : fromAddress;
                emailMessage.Subject = subject;
                emailMessage.Body = body;
                emailMessage.IsBodyHtml = true;

                if (!Regex.IsMatch(emailMessage.Body, @"^([0-9a-z!@#\$\%\^&\*\(\)\-=_\+])", RegexOptions.IgnoreCase) ||
                        !Regex.IsMatch(emailMessage.Subject, @"^([0-9a-z!@#\$\%\^&\*\(\)\-=_\+])", RegexOptions.IgnoreCase))
                {
                    emailMessage.BodyEncoding = Encoding.UTF8;
                }

                smtpSend.Send(emailMessage);
            }
        }
        public void SendMultiMail(System.Net.Mail.MailAddress fromAddress, ICollection<string> toEmail, string subject, string body)
        {
            string smtpUserName = System.Configuration.ConfigurationSettings.AppSettings["SmtpUserName"];
            string smtpUserPass = System.Configuration.ConfigurationSettings.AppSettings["SmtpUserPass"];
            string smtpServer = System.Configuration.ConfigurationSettings.AppSettings["SmtpServer"];
            string smtpMail = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
            string smtpName = System.Configuration.ConfigurationSettings.AppSettings["AdminName"];

            System.Net.Mail.SmtpClient smtpSend = new System.Net.Mail.SmtpClient(smtpServer);

            if (!smtpUserName.Equals("") && !smtpUserPass.Equals(""))
            {
                smtpSend.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpUserPass);
            }

            using (System.Net.Mail.MailMessage emailMessage = new System.Net.Mail.MailMessage())
            {
                foreach (string address in toEmail)
                    emailMessage.To.Add(address);
                //emailMessage.To.Add(toAddress);
                emailMessage.From = fromAddress.Equals(null) ? new System.Net.Mail.MailAddress(smtpMail, smtpName) : fromAddress;
                emailMessage.Subject = subject;
                emailMessage.Body = body;
                emailMessage.IsBodyHtml = true;

                if (!Regex.IsMatch(emailMessage.Body, @"^([0-9a-z!@#\$\%\^&\*\(\)\-=_\+])", RegexOptions.IgnoreCase) ||
                        !Regex.IsMatch(emailMessage.Subject, @"^([0-9a-z!@#\$\%\^&\*\(\)\-=_\+])", RegexOptions.IgnoreCase))
                {
                    emailMessage.BodyEncoding = Encoding.UTF8;
                }

                smtpSend.Send(emailMessage);
            }
        }
        
        // Vi du tao tham so mail
        public string Text2Html(string html)
        {
            html = html.Replace("\r\n", "<br/>");
            html = html.Replace("\n", "<br/>");
            return html;
        }        

        private void Test()
        {
            StringDictionary emailParams = new StringDictionary();

            emailParams["{forumname}"] = "Nguyen Van Tinh";
            emailParams["{topic}"] = "The thao";
            emailParams["{link}"] = "";//String.Format("{0}{1}", "url", "actile")

            string body = this.CreateEmailFromTemplate("pathRoot", "topicpost.txt", ref emailParams);
        }
        private void SendMailTest()
        {
            //  Build a MailMessage
            string body = this.ReadTemplate("root", "verifyemail.txt");
            body = body.Replace("{link}", "");
            body = body.Replace("{key}", "");
            body = body.Replace("{name}", "");
            body = body.Replace("{link}", String.Format("{0}", "URL"));
            //SendMail();
        }

        /// <summary>
        /// send with gmail
        /// </summary>
        /// <param name="sFromEmail"></param>
        /// <param name="sToEmail"></param>
        /// <param name="sHeader"></param>
        /// <param name="sMessage"></param>
        public void SendMailInGmail(string sFromEmail, string sToEmail, string sHeader, string sMessage)
        {
            string smtpServer = System.Configuration.ConfigurationSettings.AppSettings["SmtpServer"];
            string smtpUserName = System.Configuration.ConfigurationSettings.AppSettings["SmtpUserName"];
            string smtpUserPass = System.Configuration.ConfigurationSettings.AppSettings["SmtpUserPass"];
            string smtpMail = System.Configuration.ConfigurationSettings.AppSettings["AdminEmail"];
            string smtpPort = System.Configuration.ConfigurationSettings.AppSettings["SmtpPort"];

            if (sFromEmail.Length == 0)
                sFromEmail = smtpMail;

            System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();
            Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = smtpServer;
            Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

            Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = smtpPort;
            if (true)//(fSSL)
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";

            if (smtpUserName.Length != 0)
            {
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = smtpUserName;
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = smtpUserPass;
            }

            Mail.To = sToEmail;
            Mail.From = sFromEmail;
            Mail.Subject = sHeader;
            Mail.Body = sMessage;
            Mail.BodyFormat = System.Web.Mail.MailFormat.Html;
            Mail.BodyEncoding = Encoding.UTF8;

            System.Web.Mail.SmtpMail.SmtpServer = smtpServer;
            System.Web.Mail.SmtpMail.Send(Mail);
        }

        #endregion

    }
}
